# encoding=utf-8
from storages import cache, database
from constant.const import const
from utils.string import dir2obj, str2dir
from entity.entity import category
from storages.database import database


def sync_catrgory():
    d = database()
    c = cache.cache().get_all_map(const.category_entity)
    values = ''
    for (i, m) in c:
        s = str2dir(str(m, encoding="utf-8"))
        obj = dir2obj(s, category)
        values += '(\'' + obj.id + '\',\'' + obj.name + '\',\'' + obj.category + '\',\'' + obj.uri + '\')'
        if str(i, encoding="utf-8") != 'monthvisit':
            values += ','
    # print(values)
    d.execute("insert into " + d.database + ".book." + const.category + " values " + values)


# sync_catrgory()
# 将分类数据合并到图书列表中
def book_list_process():
    c = cache.cache()
    get = c.get_all_map(const.category)
    w = 0
    for (i, m) in get:
        if str(i, encoding="utf-8") != 'home' and str(i, encoding="utf-8") != 'quanben' and str(i,
                                                                                                encoding="utf-8") != 'monthvisit':
            name = str(i, encoding="utf-8")
            all_map = c.get_all_map(name)
            k = 0
            for (j, n) in all_map:
                book_name = str(j, encoding="utf-8")
                book_url = str(n, encoding="utf-8")
                # print(book_name + " " + book_url + " " + name)
                c.map(const.book_list, book_url, name)
                k += 1
            # print(k)
            w += k
    # print(w)


def book_list2file():
    get = cache.cache().get_all_map(const.book_list)
    for (i, m) in get:
        s = str(i, encoding="utf-8")
        with open("book_list.txt", 'a', encoding='utf-8') as f:
            f.write(s)


def read_file():
    with open("book_list.txt", 'r', encoding='utf-8') as f:
        readlines = f.readlines()
        print(readlines)


# read_file()
book_list2file()
